# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: helpers\address\__init__.py
import logging
from urllib.parse import urlparse, quote, urlunparse
import re
from netifaces import AF_INET, interfaces, ifaddresses
from urllib.parse import urlsplit, urlunsplit, parse_qs, urlencode

_logger = logging.getLogger("helpers.address")


def update_query_parameters(url, parameters):
    scheme, netloc, path, query, fragment = urlsplit(url)
    q = parse_qs(query)
    q.update(parameters)
    return urlunsplit((scheme, netloc, path, urlencode(q, doseq=True), fragment))


def remove_query_parameters(url, param_names):
    scheme, netloc, path, query, fragment = urlsplit(url)
    q = parse_qs(query)
    for param_name in param_names:
        try:
            del q[param_name]
        except KeyError:
            pass

    return urlunsplit((scheme, netloc, path, urlencode(q, doseq=True), fragment))


def get_local_addresses():
    result = set()
    for interface_name in interfaces():
        for x in ifaddresses(interface_name).get(AF_INET, tuple()):
            result.add(x["addr"])

    return result


def is_domain_label(value):
    if not value:
        return False
    elif len(value) > 63:
        return False
    else:
        alpha_test_value = value.replace("-", "1")
        alpha_test_value = alpha_test_value.replace("_", "2")
        if not alpha_test_value.isalnum():
            return False
        last_char_str = value[-1:]
        if not (last_char_str.isalpha() or last_char_str.isnumeric()):
            return False
            try:
                value.encode("idna")
            except Exception:
                return False

        return True


def extract_network_location_from_address(address, exception_on_error=False):
    try:
        parsed_address = urlparse(address)
    except Exception as e:
        if exception_on_error:
            _logger.error("parsing %s returned: %s", address, e)
            raise Exception("invalid address")
        return

    if parsed_address.scheme:
        netloc = parsed_address.netloc
    else:
        netloc = parsed_address.path
    return netloc


def extract_host_from_address(address):
    netloc = extract_network_location_from_address(address)
    parts = netloc.split("@")
    if len(parts) > 1:
        return parts[1]
    else:
        return parts[0]


def extract_domain_from_address(address):
    host = extract_host_from_address(address)
    return host.split(":")[0].lower()


def extract_base_url_from_address(address):
    try:
        parsed_address = urlparse(address)
    except Exception as e:
        _logger.error("parsing %s returned: %s", address, e)
        raise Exception("invalid address")

    if parsed_address.scheme:
        return parsed_address.scheme + "://" + parsed_address.netloc.lower() + "/"
    else:
        return "http://" + parsed_address.path.lower() + "/"


re_valid_ip = re.compile(
    "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
)


def is_ip(address):
    return re_valid_ip.match(address) is not None


def is_host(address):
    if is_ip(address):
        return True
    else:
        parts = address.split(".")
        if len(parts) > 1:
            if parts[-1] == "":
                parts = parts[:-1]
        for part in parts:
            if not is_domain_label(part):
                return False

        return True


def is_domain(address):
    if is_ip(address):
        return False
    else:
        return is_host(address)


def is_url(address):
    try:
        parsed_address = urlparse(address)
    except Exception as e:
        _logger.error("parsing %s returned: %s", address, e)
        return False

    if parsed_address.scheme not in ("https", "http"):
        return False
    else:
        parts = parsed_address.netloc.split("@")
        if len(parts) > 2:
            return False
        if len(parts) == 2:
            auth_parts = parts[0].split(":")
            if len(auth_parts) != 2:
                return False
            domain = parts[1]
        else:
            domain = parts[0]
        domain_parts = domain.split(":")
        if len(domain_parts) > 2:
            return False
        domain = domain_parts[0]
        return is_host(domain)


def encode_url(address):
    if is_domain(address):
        d = []
        for part in address.split("."):
            d.append(quote(part.encode("utf-8", errors="replace")))

        return (".").join(d)
    elif is_url(address):
        pa = urlparse(address)
        parts = pa.netloc.split("@")
        auth = None
        port = None
        if len(parts) == 2:
            auth = quote(parts[0].encode("utf-8", errors="replace"), safe=":")
            netloc = parts[1]
        else:
            netloc = parts[0]
        parts = netloc.split(":")
        if len(parts) == 2:
            port = parts[1]
        host = parts[0]
        try:
            host.encode("ascii")
        except UnicodeDecodeError:
            host = host.encode("idna")

        netloc = host
        if auth:
            netloc = auth + "@" + netloc
        if port:
            netloc = netloc + ":" + port
        path = quote(pa.path.encode("utf-8", errors="replace"), safe="/")
        params = pa.params
        query = pa.query
        fragment = pa.fragment
        return urlunparse((pa.scheme, netloc, path, params, query, fragment))
    else:
        return address


def change_url_address(url, address):
    pa = urlparse(url)
    pd = urlparse(address)
    return urlunparse((pd.scheme, pd.netloc, pa.path, pa.params, pa.query, pa.fragment))


def get_canonical_address(url):
    if is_host(url):
        domain = url
    else:
        if not is_url(url):
            return
        parsed_address = urlparse(url)
        parts = parsed_address.netloc.split("@")
        if len(parts) > 2:
            return
        if len(parts) == 2:
            auth_parts = parts[0].split(":")
            if len(auth_parts) != 2:
                return
            domain = parts[1]
        else:
            domain = parts[0]
        domain_parts = domain.split(":")
        if len(domain_parts) > 2:
            return
        domain = domain_parts[0]
        if domain == "127.0.0.1":
            domain = "localhost"
        if domain.startswith("www."):
            return domain[4:]
        return domain


def __test_get_canonical_address():
    print(get_canonical_address("https://statebank_group7.mobicloud.asu.edu/login"))
